package cn.wmingming.e3mall.manager.service.impl;

import cn.wmingming.common.jedis.JedisClient;
import cn.wmingming.common.pojo.E3Result;
import cn.wmingming.common.pojo.EasyUIDataGridResult;
import cn.wmingming.common.utils.IDUtils;
import cn.wmingming.common.utils.JsonUtils;
import cn.wmingming.e3mall.manager.service.ItemService;
import cn.wmingming.e3mall.mapper.TbItemDescMapper;
import cn.wmingming.e3mall.mapper.TbItemMapper;
import cn.wmingming.e3mall.pojo.TbItem;
import cn.wmingming.e3mall.pojo.TbItemDesc;
import cn.wmingming.e3mall.pojo.TbItemDescExample;
import cn.wmingming.e3mall.pojo.TbItemExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/***
 * 商品服务实现类
 */
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private TbItemMapper itemMapper;
    @Autowired
    private TbItemDescMapper itemDescMapper;
    @Resource
    private JmsTemplate jmsTemplate;
    @Resource
    private ActiveMQTopic topicDestination;
    @Autowired
    private JedisClient jedisClient;
    @Value("${REDIS_ITEM_PRE}")
    private String REDIS_ITEM_PRE;
    @Value("${REDIS_ITEM_EXPIRE}")
    private Integer REDIS_ITEM_EXPIRE;
    
    
    @Override
    public TbItem getItemById(long itemId) {
        //先从redis缓存中查询数据
        try{
            String s = jedisClient.get(REDIS_ITEM_PRE + ":" + itemId + "BASE");
            if(StringUtils.isNoneBlank(s)){
                TbItem tbItem = JsonUtils.jsonToPojo(s, TbItem.class);
                return tbItem;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        TbItem tbItem = itemMapper.selectByPrimaryKey(itemId);
        //将tbItem数据缓存到redis中，并设置过期时间
        try{
            jedisClient.set(REDIS_ITEM_PRE+":"+tbItem.getId()+"BASE",JsonUtils.objectToJson(tbItem));
            jedisClient.expire(REDIS_ITEM_PRE+":"+tbItem.getId()+"BASE",REDIS_ITEM_EXPIRE);
        }catch (Exception e){
            e.printStackTrace();
        }
        return tbItem;
    }

    @Override
    public EasyUIDataGridResult getItemList(int page, int rows) {
        //设置分页信息
        PageHelper.startPage(page,rows);
        TbItemExample example = new TbItemExample();
        //商品状态，1-正常，2-下架，3-删除
        example.createCriteria().andStatusNotEqualTo((byte)3);
        //执行查询
        List<TbItem> itemList = itemMapper.selectByExample(example);
        //创建返回值对象
        EasyUIDataGridResult result = new EasyUIDataGridResult();
        result.setRows(itemList);
        //获取分页结果
        PageInfo<TbItem> pageInfo = new PageInfo<>(itemList);
        result.setTotal(pageInfo.getTotal());
        return result;
    }

    /**
     * 添加商品
     * @param item
     * @param desc
     * @return
     */
    @Override
    public E3Result addItem(TbItem item, String desc) {
        Date date = new Date();
        E3Result result = null;
        //补完item
        long id = IDUtils.genItemId();
        item.setId(id);
        item.setStatus(Byte.parseByte("1") );
        item.setCreated(date);
        item.setUpdated(date);
        //保存item
        int insert1 = itemMapper.insert(item);

        TbItemDesc itemDesc = new TbItemDesc();
        //补完itemDesc
        itemDesc.setItemId(id);
        itemDesc.setCreated(date);
        itemDesc.setItemDesc(desc);
        itemDesc.setUpdated(date);
        //保存itemDesc
        int insert2 = itemDescMapper.insert(itemDesc);
        if (insert1 != 0 && insert2 != 0){
            result = E3Result.ok();
            //使用ActiveMQ发送消息通知其它应用
            jmsTemplate.send(topicDestination, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    TextMessage textMessage = session.createTextMessage();
                    textMessage.setText(id+"");
                    return textMessage;
                }
            });
        }else {
            result = E3Result.build(10010, "数据插入失败");
        }
        return result;
    }

    @Override
    public TbItemDesc getItemDesc(long id) {
        //先从redis缓存中查询数据
        try{
            String s = jedisClient.get(REDIS_ITEM_PRE + ":" + id + "DESC");
            if(StringUtils.isNoneBlank(s)){
                TbItemDesc tbItemDesc = JsonUtils.jsonToPojo(s, TbItemDesc.class);
                return tbItemDesc;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        TbItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(id);
        //将tbItem数据缓存到redis中，并设置过期时间
        try{
            jedisClient.set(REDIS_ITEM_PRE+":"+itemDesc.getItemId()+"DESC",JsonUtils.objectToJson(itemDesc));
            jedisClient.expire(REDIS_ITEM_PRE+":"+itemDesc.getItemId()+"DESC",REDIS_ITEM_EXPIRE);
        }catch (Exception e){
            e.printStackTrace();
        }
        return itemDesc;
    }

    @Override
    public E3Result updateItem(TbItem item, String desc) {
        Date date = new Date();
        item.setUpdated(date);
        TbItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(item.getId());
        itemDesc.setUpdated(date);
        itemDesc.setItemDesc(desc);
        itemMapper.updateByPrimaryKeySelective(item);
        itemDescMapper.updateByPrimaryKeySelective(itemDesc);
        //删除缓存
        delSyncCatch(item.getId());
        return E3Result.ok();
    }

    @Override
    public E3Result deleteItem(String ids) {
        return itemStatus(ids,3);
    }

    @Override
    public E3Result instockItem(String ids) {
        return itemStatus(ids,2);
    }

    @Override
    public E3Result reshelfItem(String ids) {
        return itemStatus(ids,1);
    }

    /**
     *
     * @param ids
     * @param status 商品状态，1-正常，2-下架，3-删除
     * @return
     */
    private E3Result itemStatus(String ids,int status){
        String[] split = ids.split(",");
        List<Long> idList = new ArrayList<>();
        for (String id:split){
            idList.add(Long.valueOf(id));
            //删除缓存
            delSyncCatch(Long.valueOf(id));
        }
        TbItemExample example = new TbItemExample();
        example.createCriteria().andIdIn(idList);
        TbItem item = new TbItem();
        item.setStatus((byte)status);
        itemMapper.updateByExampleSelective(item,example);
        return E3Result.ok();
    }

    /**
     * 如果缓存中存在该id的数据，就从redis中删除缓存
     * @param id 商品的id
     */
    private void delSyncCatch(Long id){
        if(jedisClient.exists(REDIS_ITEM_PRE+id+"BASE"))
            jedisClient.del(REDIS_ITEM_PRE+id+"BASE");
        if(jedisClient.exists(REDIS_ITEM_PRE+id+"DESC"))
            jedisClient.del(REDIS_ITEM_PRE+id+"DESC");
    }
}
